<template>
  <base-dialog
    class="add-dept"
    ref="baseDialogRef"
    v-bind="$attrs"
    :model-value="modelValue"
    @cancel="handleCancel"
    @confirm="handleConfirm"
    :confirm-btn="{ loading: submitLoading }"
    @close="handleCancel"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" @submit.prevent>
      <el-form-item prop="deptName">
        <el-input v-model="formData.deptName" placeholder="请输入下级组织名称" :maxlength="10" show-word-limit />
      </el-form-item>
    </el-form>
  </base-dialog>
</template>

<script setup>
  // 定义 props
  const props = defineProps({
    // v-model
    modelValue: {
      type: Boolean,
      default: false,
    },
    // 组织信息
    deptInfo: {
      type: Object,
      default: () => ({}),
    },
  });

  // 定义 emits 事件
  const emits = defineEmits(["update:modelValue", "success", "fail"]);

  // 表单组件实例
  const formRef = ref(null);

  // 表单数据
  const formData = ref({
    parentId: null,
    deptName: "",
  });

  // 表单校验规则
  const rules = {
    deptName: [
      { required: true, message: "请输入下级组织名称", trigger: "blur" },
      { min: 1, max: 10, message: "下级名称长度在 1 到 10 个字符", trigger: "blur" },
    ],
  };

  // 监听弹窗状态和组织信息变化，更新表单
  watch(
    [() => props.modelValue, () => props.deptInfo],
    ([isVisible, deptInfo]) => {
      if (isVisible && deptInfo) {
        // 只在弹窗打开且有数据时才更新
        formData.value = {
          deptName: "",
          parentId: deptInfo.id || 0,
        };
      } else if (!isVisible) {
        // 弹窗关闭时重置表单
        formData.value = {
          parentId: null,
          deptName: "",
        };
        // 清除验证状态
        nextTick(() => {
          formRef.value?.clearValidate();
        });
      }
    },
    { immediate: true }
  );

  // 确认按钮回调
  const handleConfirm = () => {
    formRef.value.validate(valid => {
      if (!valid) return;
      loadAddDept();
    });
  };

  // 提交 loading
  const submitLoading = ref(false);

  // 发送新增下级请求
  const loadAddDept = () => {
    submitLoading.value = true;
    Api.dept
      .AddDept(formData.value)
      .then(() => {
        $msg.success("新增成功");
        emits("success");
        emits("update:modelValue", false);
      })
      .catch(err => {
        emits("fail", err);
      })
      .finally(() => {
        submitLoading.value = false;
      });
  };

  // 取消按钮回调
  const handleCancel = () => {
    formRef.value.resetFields();
    emits("update:modelValue", false);
  };
</script>
<style lang="scss">
  .add-dept {
    .el-dialog__footer {
      padding-top: 14px !important;
    }
  }
</style>
